/**
 * Created by xiazi on 2019/12/4.
 */
var recordId = 0;
var showChatWindow, showFriends, initWechatBox;
var showChatRecords;
var showFriendInfo;
var sendMsgToFriend;
var getFriends;
var getChats;
var getChatsById;// 获取用户聊天记录
var deleteFriend;
var friends;
var new_msg;
var chatRecords;
var sendMsg;
var getStrangers;
var showStrangerInfo;
var getStrangerInfo;
var acceptStranger;
var replyStranger;
var showAddFriend;
var showEmojiPanel;
var layer;
var $;
var flow;
var voice;
var getChatRecord;
var getWeChats;
var getMedia;
var checkingDownloadStatus;
var getFriendSnsPages;
var viewOuterContent;
var getSnsMedia;
var checkingSnSDownloadStatus;
var getCustomerInfo;
var showCustomerInfo;
var getMediaV2;
var requestSyncFriends;
var newStranger;

var getMaterialGroups;
var getMaterials;
var sendMaterial;

var showSendImg;

var setMsgRead;
var buildWeChat;

var showSnsTabContent;
var showMaterialTabContent;
// 同步消息
var syncMsg = function () {
    var currWechat = $('#wechat_tab_wrap .layui-tab-title .layui-this')
    if (currWechat.html()) {
        service.post('api/v1/wxinfo/syncmsg', {id: parseInt(currWechat.attr('lay-id'))}).then((res) => {
            if (res.code === 200) {
                var msgs = res.data.Data.AddMsgs;
                if (msgs.length > 0) {
                    $.each(msgs, function (i, msg) {
                        new_msg(p);
                    });
                }
            } else {
                layer.msg(res.msg, {offset: '45vh', icon: 5, time: 2000});
            }
        }).catch((err) => {
            layer.msg(err.msg, {offset: '45vh', icon: 5, time: 2000});
        })
    }
}

setTimeout(syncMsg, 2000)

showFriends = function (elemId, boardId) {
    var obj = $("#" + elemId);
    obj.find(".wechat_board_right_friends").css("display", "block");
    obj.find(".wechat_board_right_chat").css("display", "none");
    obj.find(".board_swich_chat").css("color", "#c2c2c2");
    obj.find(".board_swich_friend").css("color", "#5FB878");
    obj.find(".wechat_board_right_tags").css("display", "none");
    obj.find(".board_swich_tag").css("color", "#c2c2c2");
    var searchObj = $('#board' + boardId).find('input[name=search_friend]');
    searchObj.val('');
    rebuildFriendList(boardId);
    // getStrangers(boardId);
    getFriends(boardId);
    requestSyncFriends(boardId);
    showStrangerDot(false, boardId);


    var height = $('#LAY_wechat_content').height();
    var strangerListHeight = (height - 42 - 48 - 42 - 42 - 14);
    obj.find(".wechat_stranger_list").height(strangerListHeight + "px");
    var friendListHeight = (height - 42 - 48 - 42 - 42 - 14);
    obj.find(".wechat_friend_list").height(friendListHeight + "px");
};

var rebuildFriendList = function (boardId) {
    var listObj = $('#wechat_friend_list_' + boardId);
    var listParentObj = listObj.parent();
    listObj.remove();
    listParentObj.append('<div class="layui-col-sm12 wechat_friend_list" id="wechat_friend_list_' + boardId + '" style="overflow: hidden;overflow-y:auto; ">');
};

var rebuildChatList = function (boardId) {
    var listObj = $('#wechat_chat_list_' + boardId);
    var listParentObj = listObj.parent();
    listObj.remove();
    listParentObj.append('<div class="layui-col-sm12 wechat_chat_list" id="wechat_chat_list_' + boardId + '" style="overflow: hidden;overflow-y:auto; ">');
};

var showDot = function (display, boardId, friendId, unreadMsgCount, weChatUnreadMsgCount) {
    if (unreadMsgCount == undefined) {
        unreadMsgCount = 0;
    }
    if (weChatUnreadMsgCount == undefined) {
        weChatUnreadMsgCount = '';
    }
    var unreadMsgCountBadge = 'layui-badge';//'layui-badge-dot';
    var board, weChatList, weChatNav, tab, swichChat, chatList, chat, weChatDot, tabDot, swichDot, chatDot;
    board = $('#board' + boardId);
    weChatList = $('#LAY_wechat_list');
    weChatNav = weChatList.find("a[data-id=" + boardId + "]");
    weChatDot = weChatNav.find('.' + unreadMsgCountBadge);
    tab = $('.layui-tab-card').find("li[lay-id=" + boardId + "]");
    if (tab) {
        tabDot = tab.find('.' + unreadMsgCountBadge);
    }
    swichChat = board.find('.board_swich_chat');
    swichDot = swichChat.find('.' + unreadMsgCountBadge);
    if (friendId) {
        chatList = board.find('.wechat_chat_list');
        if (chatList) {
            chat = chatList.find('#friend' + friendId);
            chatDot = chat.find('.' + unreadMsgCountBadge);
        }
    }
    if (display == true) {
        if (weChatDot) {
            weChatDot.remove();
            if (weChatUnreadMsgCount > 0) {
                weChatNav.append('<span class="' + unreadMsgCountBadge + '" style="position: absolute;right:1px;z-index: 999999;">' + weChatUnreadMsgCount + '</span>');
            }
        }
        if (tabDot) {
            tabDot.remove();
            if (weChatUnreadMsgCount > 0) {
                tab.append('<span class="' + unreadMsgCountBadge + '" style="position: absolute;left:1px;z-index: 999999;">' + weChatUnreadMsgCount + '</span>');
            }
        }
        if (swichDot) {
            swichDot.remove();
            if (weChatUnreadMsgCount > 0) {
                swichChat.append('<span class="' + unreadMsgCountBadge + '" style="position: absolute;left:1px;z-index: 999999;">' + weChatUnreadMsgCount + '</span>');
            }
        }
        if (chatDot) {
            chatDot.remove();
            if (chat && unreadMsgCount > 0) {
                chat.append('<span class="' + unreadMsgCountBadge + '" style="position: absolute;right:1px;z-index: 999999;">' + unreadMsgCount + '</span>');
            }
        }
        voice();
    } else {
        if (weChatDot) weChatDot.remove();
        if (tabDot) tabDot.remove();
        if (swichDot) swichDot.remove();
        if (chatDot) chatDot.remove();
        if (friendId > 0) {
            setMsgRead(boardId, friendId);
        }
    }
};

var showStrangerDot = function (display, boardId) {
    var board = $('#board' + boardId);
    var swichFriend = board.find('.board_swich_friend');
    var swichDot = swichFriend.find('.layui-badge-dot');
    if (display == true) {
        if (swichDot) {
            swichDot.remove();
            swichFriend.append('<span class="layui-badge-dot" style="position: absolute;right:1px;z-index: 999999;"></span>');
        }
    } else {
        if (swichDot) swichDot.remove();
    }
};

var showStrangerTabDot = function (display, boardId) {
    var board = $('#board' + boardId);
    var strangerTab = board.find('.stranger_tab');
    var dot = strangerTab.find('.layui-badge-dot');
    if (display == true) {
        if (dot) {
            dot.remove();
            strangerTab.append('<span class="layui-badge-dot"></span>');
        }
    } else {
        if (dot) dot.remove();
    }
};

var showStrangerItemDot = function (display, strangerId) {
    var strangerDot = $('#stranger' + strangerId).find('.layui-badge-dot');
    if (display == true) {

    } else {
        if (strangerDot) strangerDot.remove();
    }
};

layui.use(['element', 'laytpl', 'form', 'table', 'upload'], function () {
        $ = layui.jquery
            , layer = layui.layer
            , flow = layui.flow
            , element = layui.element
            , form = layui.form
            , util = layui.util
            , device = layui.device()
            , $win = $(window)
            , $body = $('body')
            , laytpl = layui.laytpl
            , upload = layui.upload;

        var table = layui.table;

        element.init();

        $body.on('click', '*[layim-event]', function (e) {
            var othis = $(this), methid = othis.attr('layim-event');
            events[methid] ? events[methid].call(this, othis, e) : '';
        });

        var events = {
            playAudio: function (othis) {
                var audioData = othis.data('audio')
                    , audio = audioData || document.createElement('audio')
                    , pause = function () {
                    audio.pause();
                    othis.removeAttr('status');
                    othis.find('i').html('&#xe652;');
                };
                if (othis.data('error')) {
                    return layer.msg('语音消息播放异常');
                }
                if (!audio.play) {
                    return layer.msg('您的浏览器不支持audio，请使用谷歌浏览器');
                }
                if (othis.attr('status')) {
                    pause();
                } else {
                    audioData || (audio.src = othis.data('src'));
                    audio.play();
                    othis.attr('status', 'pause');
                    othis.data('audio', audio);
                    othis.find('i').html('&#xe651;');
                    //播放结束
                    audio.onended = function () {
                        pause();
                    };
                    //播放异常
                    audio.onerror = function () {
                        layer.msg('语音消息播放异常');
                        othis.data('error', true);
                        pause();
                    };
                }
            }
        };

        //触发事件
        var active = {
            tabAdd: function (title, id) {
                //新增一个Tab项
                element.tabAdd('wechat', {
                    title: title
                    , content: showWechatBoard(id)
                    , id: id
                });
                initWechatBox(id);
            }
            , tabChange: function (id) {
                //切换到指定Tab项
                element.tabChange('wechat', id);
                $('.layui-tab-item').css('height', '100%');
                autodivheight();
                showDot(false, id, 0);
            }
        };

        voice = function () {
            if (device.ie && device.ie < 9) return;
            var audio = document.createElement("audio");
            audio.src = '/assets/voice/new_msg.mp3';
            audio.autoplay = true;
            audio.load();
        };

        var showWechatBoard = function (boardId) {
            var board_html = '';
            var fresh = true;
            var getTpl = tpl_wechat_board.innerHTML;
            var data = {"boardId": boardId};
            laytpl(getTpl).render(data, function (html) {
                board_html = html;
            });
            getWechatInfo(boardId, fresh);
            return board_html;
        };

        initWechatBox = function (wechatId) {
            getChats(wechatId, 1);
        };

        new_msg = function (msg, newChat, wechatId) {
            var notify = false;
            if (msg['notify'] && msg['notify'] == true) {
                notify = true;
            }
            if (newChat == true) {
                addNewChat(msg['wechat_id'], msg['friend_id'], notify);
            }
            // if (msg['notify'] && msg['notify']==true) {
            //     showDot(true, msg['wechat_id'], msg['friend_id']);
            // }
            msg.isRecipient = wechatId == msg.ToUserName // 是否是接收者
            var board_html = '';
            var getTpl = tpl_msg.innerHTML;
            var data = {"msg": msg};
            laytpl(getTpl).render(data, function (html) {
                board_html = $.trim(html);
            });
            if (board_html && board_html !== '') {
                var elm = document.getElementById('record_' + msg['id']);
                if (elm) {//消息已展示
                    var record = $('#record_' + msg['record_id']);
                    record.find('.layui-icon-loading').css('display', 'none');
                    if (msg['status'] == -1 && msg['remark'] != '') {
                        record.find('.msg_remark').html('<i class="layui-icon layui-icon-tips" style="padding:0;color:red;"><label>' + msg['remark'] + '</label></i>');
                    }
                } else {//消息未展示
                    var friend_id = wechatId === msg['FromUserName'] ? msg['ToUserName'] : msg['FromUserName']
                    var obj = $('#friendChat_' + wechatId + '_' + friend_id).find('.layim-chat-main');
                    var ulObj = obj.find('ul');
                    var firstObj = ulObj.find('li').first();
                    var lastObj = ulObj.find('li').last();
                    var scroll = false;
                    if (lastObj.is('li') && firstObj.is('li')) {
                        var firstId = firstObj.attr('id');
                        var lastId = lastObj.attr('id');
                        lastId = Number(lastId.replace('record_', ''));
                        firstId = Number(firstId.replace('record_', ''));
                        if (msg['id'] > lastId) {//新消息
                            lastObj.after(board_html);
                            scroll = true;
                        } else if (msg['id'] < firstId) {//旧消息
                            firstObj.before(board_html);
                        }
                    } else {//初始化加载消息
                        ulObj.html(board_html);
                    }
                    if (scroll === true) {
                        elm = document.getElementById('record_' + msg['id']);
                        if (elm) {
                            elm.scrollIntoView();
                        }
                    }
                }
            }

        };

        sendMsg = function (boardId, wechatId, friendId) {
            var obj = $('#board' + boardId).find('.new-chat-message');
            if (obj) {
                var textMsg = $.trim(obj.val())
                if (textMsg == '') {
                    layer.msg('消息内容不能为空', {offset: '45vh', icon: 5, time: 2000});
                    return false;
                }
                var post = {
                    id: parseInt(boardId),
                    context: textMsg,
                    searchWxIds: [friendId]
                };
                layer.msg('发送中...', {
                    shadeClose: false
                    , icon: 16
                    , shade: 0.01
                    , time: 500
                });
                service.post('api/v1/wxinfo/sendtxtmsg', post).then((res) => {
                    if (res.code === 200) {
                        getChatsById(boardId, 1)
                        obj.val('');
                    } else {
                        layer.msg(res.msg, {offset: '45vh', icon: 5, time: 2000});
                    }
                }).catch((err) => {
                    layer.msg(err.msg, {offset: '45vh', icon: 5, time: 2000});
                })
            }
        };

        newStranger = function (msg) {
            if (msg['notify'] && msg['notify'] == true) {
                showStrangerDot(true, msg['wechat_id']);
            }
        };

        showChatWindow = function (elemId, boardId, rebuild, friendId) {
            var obj = $("#" + elemId);
            obj.find(".wechat_board_right_friends").css("display", "none");
            obj.find(".wechat_board_right_chat").css("display", "block");
            obj.find(".wechat_board_right_more_window").css("display", "block");
            obj.find(".board_swich_chat").css("color", "#5FB878");
            obj.find(".board_swich_friend").css("color", "#c2c2c2");
            obj.find(".wechat_board_right_tags").css("display", "none");
            obj.find(".board_swich_tag").css("color", "#c2c2c2");

            var searchObj = $('#board' + boardId).find('input[name=search_chat]');
            searchObj.val('');
            getChats(boardId, rebuild, friendId);

            var height = $('#LAY_wechat_content').height();
            var chatListHeight = (height - 42 - 48);
            $(".wechat_chat_list").height(chatListHeight + "px");
        };


        var getWechatInfo = function (wechatId, fresh) {
            service.post('api/v1/wxinfo/getcontractlist', {id: parseInt(wechatId)}).then((res) => {
                if (res.code === 0) {
                    var wechatInfo = res.data;
                    if (fresh == true && wechatInfo.headImage && wechatInfo.headImage != '') {
                        $('#headImage' + wechatId).attr('src', wechatInfo.headImage);
                    }
                } else {
                    layer.msg(res.msg, {offset: '45vh', icon: 5, time: 2000});
                }
            }).catch((err) => {
                layer.msg(err.msg, {offset: '45vh', icon: 5, time: 2000});
            })
        };

        // 创建微信号列表
        buildWeChat = function (weChatData) {
            return '<dd id="w_' + (weChatData.id != '' ? weChatData.id : '') + '"><a data-name="' + (weChatData.nickName != '' ? weChatData.nickName : weChatData.wxId) + '" data-id="' + (weChatData.id != '' ? weChatData.id : '') + '" class="layui-side-wechat" data-type="tabChange"><span class="layui-badge" style="position: absolute;right:1px;z-index: 999999;' + (weChatData.unread_msg_count > 0 ? '' : 'display: none;') + '">' + weChatData.unread_msg_count + '</span>' + (weChatData.online === 10 ? '<span style="float:right;color: green;">在线</span>' : '<span style="float:right;color: red;">离线</span>') + '<img src="' + (weChatData.headImg ? weChatData.headImg : '../assets/images/default_head.jpeg') + '" width="30px">&nbsp;' + (weChatData.nickName != '' ? weChatData.nickName : weChatData.wxId) + '</a></dd>';
        };


        // 获得当前用户的微信号列表
        getWeChats = function () {//已改成流加载
            layui.use('flow', function () {
                var flow = layui.flow;
                var element = layui.element;
                element.init();
                flow.load({
                    elem: '#LAY_wechat_list' //指定列表容器
                    , scrollElem: '#LAY_wechat_list'
                    , done: function (page, next) { //到达临界点（默认滚动触发），触发下一页
                        var lis = [];

                        service.post('api/v1/wxinfos', {
                            page: page,
                            user_id: layui.data('ACCOUNT_ID').ACCOUNT_ID
                        }).then((res) => {
                            if (res.code === 0) {
                                var weChats = res.data;
                                layui.each(weChats, function (index, item) {
                                    var str = buildWeChat(item);
                                    var wObj = $('#w_' + item.id);
                                    var wHtml = wObj.html();
                                    if (wHtml) {
                                        wObj.remove();
                                        $('#LAY_wechat_list').first().prepend(str);
                                    } else {
                                        lis.push(str);
                                    }
                                });
                                next(lis.join(''), page < res.pages);

                                $(".layui-side-wechat").click(function () {
                                    var wechatObj = $(this);
                                    if ($(".layui-tab-title li[lay-id]").length <= 0) {
                                        active.tabAdd(wechatObj.attr("data-name"), wechatObj.attr("data-id"));
                                    } else {
                                        var isData = false;
                                        $.each($(".layui-tab-title li[lay-id]"), function () {
                                            if ($(this).attr("lay-id") == wechatObj.attr("data-id")) {
                                                isData = true;
                                            }
                                        });
                                        if (isData == false) {
                                            active.tabAdd(wechatObj.attr("data-name"), wechatObj.attr("data-id"));
                                        }
                                    }
                                    active.tabChange(wechatObj.attr("data-id"));
                                });
                            } else {
                                layer.msg(res.msg, {offset: '45vh', icon: 5, time: 2000});
                            }
                        }).catch((err) => {
                            layer.msg(err.msg, {offset: '45vh', icon: 5, time: 2000});
                        })
                    }
                });
            });
        };

        getChatsById = function (boardId, page) {
            service.post('api/v1/wxinfo/syncmsg', {id: parseInt(boardId), page: page}).then((res) => {
                if (res.code === 0) {
                    new_msg(res.data.history, false, res.data.wxId)
                } else {
                    layer.msg(res.msg, {offset: '45vh', icon: 5, time: 2000});
                }
            }).catch((err) => {
                layer.msg(err.msg, {offset: '45vh', icon: 5, time: 2000});
            })
        }

        // 解析会话列表
        var parserChat = function (item, boadrId, wechatId) {
            if (item.FromUserName === wechatId) { // 如果消息来源是当前的微信
                if (item.ToUserName.indexOf('chatroom') === -1 && item.ToUserName.indexOf('gh_') === -1) {
                    return '<div class="layui-row layui-col-space5" style="margin:1px;background: #ffffff;" id="friend' + item.ToUserName + '"' + `onclick=showChatRecords(${boadrId},'${item.FromUserName}','${item.ToUserName}','${item.toname}',2)>` + '<div class="layui-col-sm3"><img src="' + (item.fromavatar ? item.toavatar : '../assets/images/default_head.jpeg') + '" style="width: 100%; height: 100%;"></div><div class="layui-col-sm9" style="height: 100%;"><span style="float: left;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">' + (item.toname != '' ? item.toname : '') + '</span><span style="position: relative;float: right;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;"></span><span class="layui-form-mid layui-word-aux" style="width:90%;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">' + (item.Content || '') + '</span></div><span class="layui-badge" style="display:none;position: absolute;right:1px;z-index: 999999;">' + item.unread_msg_count + '</span></div>';
                }
            } else {
                if (item.FromUserName.indexOf('chatroom') === -1 && item.FromUserName.indexOf('gh_') === -1) {
                    return '<div class="layui-row layui-col-space5" style="margin:1px;background: #ffffff;" id="friend' + item.ToUserName + '"' + `onclick=showChatRecords(${boadrId},'${item.ToUserName}','${item.FromUserName}','${item.fromname}',2)>` + '<div class="layui-col-sm3"><img src="' + (item.fromavatar ? item.fromavatar : '../assets/images/default_head.jpeg') + '" style="width: 100%; height: 100%;"></div><div class="layui-col-sm9" style="height: 100%;"><span style="float: left;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">' + (item.fromname != '' ? item.fromname : '') + '</span><span style="position: relative;float: right;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;"></span><span class="layui-form-mid layui-word-aux" style="width:90%;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">' + (item.Content || '') + '</span></div><span class="layui-badge" style="display:none;position: absolute;right:1px;z-index: 999999;">' + item.unread_msg_count + '</span></div>';
                }
            }
        };

        var chats;
        // 获取会话列表
        getChats = function (boardId, rebuild, friendId) {
            if (rebuild == 1) {
                rebuildChatList(boardId);
            }
            layui.use('flow', function () {
                var flow = layui.flow;
                var element = layui.element;
                element.init();

                flow.load({
                    elem: '#wechat_chat_list' + boardId //指定列表容器
                    , scrollElem: '.wechat_chat_list'
                    , done: function (page, next) { //到达临界点（默认滚动触发），触发下一页
                        var lis = [];
                        var obj = $('#board' + boardId).find('input[name=search_chat]');
                        var search_chat = obj.val();
                        var post = {
                            search: encodeURIComponent(search_chat),
                            page: page,
                            limit: 10
                        };

                        // service.post('api/v1/wxinfo/twicelogin', {id: parseInt(boardId)}).then((response) => {
                        //     if (response.code === 200) {
                        service.post('api/v1/wxinfo/conversion', {id: parseInt(boardId)})
                            .then((res) => {
                                //假设你的列表返回在data集合中
                                if (res.code === 0) {
                                    chats = res.data.conversion;
                                    layui.each(chats, function (index, item) {
                                        var str = parserChat(item, boardId, res.data.wxId);
                                        lis.push(str);
                                    });
                                    next(lis.join(''), false);
                                } else {
                                    layer.msg(res.msg, {offset: '45vh', icon: 5, time: 2000});
                                }
                            }).catch((err) => {
                            layer.msg(err.msg, {offset: '45vh', icon: 5, time: 2000});
                        })
                        //     } else {
                        //         layer.msg(response.msg, {icon: 5});
                        //     }
                        // }).catch((err) => {
                        //     layer.msg(err.msg, {offset: '45vh', icon: 5, time: 2000});
                        // })
                    }
                });
            });

            if (friendId > 0) {
                addNewChat(boardId, friendId);
            }
        };

        var addNewChat = function (boardId, friendId, notify, rebuild) {
            var post = {
                search: '',
                page: 1,
                limit: 1
            };
            // $.ajax({
            //     type: "POST",
            //     url: "/cs_work/get_chats_ajax/" + boardId + '/' + friendId,
            //     data: post,
            //     success: function (response) {
            var dataObj = {
                "code": 0,
                "data": [{
                    "wechat_id": 149872,
                    "friend_id": "4",
                    "friend_name": "\u5fae\u4fe1\u56e2\u961f",
                    "friend_username": "weixin",
                    "friend_small_head_image": "http:\/\/wx.qlogo.cn\/mmhead\/cypR72jV8BHjDwNh3Nc1YcsgzmiaZacpR1dgiaibt4QuMs\/96",
                    "content": "\u6b22\u8fce\u4f60\u518d\u6b21\u56de\u5230\u5fae\u4fe1\u3002\u5982\u679c\u4f60\u5728\u4f7f\u7528\u8fc7\u7a0b\u4e2d\u6709\u4efb\u4f55\u7684\u95ee\u9898\u6216\u5efa\u8bae\uff0c\u8bb0\u5f97\u7ed9\u6211\u53d1\u4fe1\u53cd\u9988\u54e6\u3002",
                    "send_date": "2019-11-29 13:49:08",
                    "msg_type": "1",
                    "friend_type": 1,
                    "unread_msg_count": "0"
                }],
                "pages": 1,
                "wechat_unread_msg_count": "0"
            }
            if (dataObj.code === 0) {
                chats = dataObj.data;
                var board_html = '';
                var obj = $('#board' + boardId).find('.wechat_chat_list');
                layui.each(chats, function (index, item) {
                    board_html = parserContractList(item);
                    //移除原来的记录再插入
                    if (board_html && board_html != '') {
                        if (notify == true || rebuild == true) {
                            obj.find('div[id=friend' + friendId + ']').remove();
                            obj.first().prepend(board_html);
                        }
                        if (notify == true) {
                            showDot(true, boardId, friendId, item.unread_msg_count, dataObj.wechat_unread_msg_count);
                        }
                    }
                });
            } else {
                layer.msg(dataObj.msg, {icon: 5});
            }
            // },
            // error: function (request, status, error) {
            //     layer.msg('哦噢，网络开小差了', {icon: 5});
            // }
            // });
        };

        // 解析微信联系人列表
        var parserContractList = function (item) {
            if (item.wxId && item.wxId.indexOf('gh_') === -1) {
                return '<div class="layui-row layui-col-space5" style="margin:1px;background: #ffffff;" id="friend' + item.wxId + '"' + `onclick=showChatRecords(${item.accountId},'${item.ourWxId}','${item.wxId}','${item.nick_name}',2)>` + '<div class="layui-col-sm3"><img src="' + (item.fromavatar ? item.fromavatar : '../assets/images/default_head.jpeg') + '" style="width: 100%; height: 100%;"></div><div class="layui-col-sm9" style="height: 100%;"><span style="float: left;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">' + (item.fromname != '' ? item.fromname : '') + '</span><span style="position: relative;float: right;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;"></span><span class="layui-form-mid layui-word-aux" style="width:90%;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">' + (item.Content ? item.Content : '') + '</span></div><span class="layui-badge" style="display:none;position: absolute;right:1px;z-index: 999999;">' + item.unread_msg_count + '</span></div>';
            }
        };

        // 获取微信联系人列表
        getFriends = function (boardId, click) {//已改成流加载
            const searchVal = $.trim($('#search_friend').val())
            if (click == true) {
                rebuildFriendList(boardId);
            }
            layui.use('flow', function () {
                var flow = layui.flow;
                var element = layui.element;
                element.init();

                flow.load({
                    elem: '#wechat_friend_list_' + boardId //指定列表容器
                    , scrollElem: '.wechat_friend_list'
                    , done: function (page, next) { //到达临界点（默认滚动触发），触发下一页
                        var lis = [];
                        var obj = $('#board' + boardId).find('input[name=search_friend]');
                        var search_friend = obj.val();

                        service.post('api/v1/wxinfo/getcontractlist', {id: parseInt(boardId)}).then((res) => {
                            if (res.code === 0) {
                                friends = res.data;
                                layui.each(friends, function (index, item) {
                                    if (item.wxId.indexOf('gh_') === -1) {
                                        var str = ''
                                        if (searchVal) {
                                            if (item.nick_name.indexOf(searchVal) !== -1 || item.remark.indexOf(searchVal) !== -1) {
                                                str = `<div class="layui-row layui-col-space5" style="margin:1px;background: #f9f9f9;" id="${item.id}" onclick="showFriendInfo('${boardId}','${item.ourWxId}','${item.wxId}','${item.nick_name}','${item.remark}','${item.avatar}','${item.province}','${item.city}','${item.sex}',${item.id})"><div class="layui-col-sm3"><img src="${item.avatar || '../assets/images/default_head.jpeg'}" style="width: 100%; height: 100%;"></div><div class="layui-col-sm9"><span>${item.remark || item.nick_name}</span></div></div>`;
                                            }
                                        } else {
                                            str = `<div class="layui-row layui-col-space5" style="margin:1px;background: #f9f9f9;" id="${item.id}" onclick="showFriendInfo('${boardId}','${item.ourWxId}','${item.wxId}','${item.nick_name}','${item.remark}','${item.avatar}','${item.province}','${item.city}','${item.sex}',${item.id})"><div class="layui-col-sm3"><img src="${item.avatar || '../assets/images/default_head.jpeg'}" style="width: 100%; height: 100%;"></div><div class="layui-col-sm9"><span>${item.remark || item.nick_name}</span></div></div>`;
                                        }
                                        lis.push(str);
                                    }
                                });
                                next(lis.join(''), false);
                            } else {
                                layer.msg(res.msg, {offset: '45vh', icon: 5, time: 2000});
                            }
                        }).catch((err) => {
                            layer.msg(err.msg, {offset: '45vh', icon: 5, time: 2000});
                        })
                    }
                });
            });
        };

        requestSyncFriends = function (weChatId) {
            // $.ajax({
            //     type: "GET",
            //     url: "/cs_work/newFriendsTask/" + weChatId,
            //     success: function (response) {
            //         var dataObj = $.parseJSON(response);
            //         var dataObj = {"code": -1, "msg": "\u8bf7\u6c42\u540c\u6b65\u597d\u53cb\u5931\u8d25"};
            //         if (dataObj.code === 0) {
            //
            //         } else {
            //             layer.msg(dataObj.msg, {icon: 5});
            //         }
            //     },
            //     error: function (request, status, error) {
            //         layer.msg('哦噢，网络开小差了', {icon: 5});
            //     }
            // });
        };

        // 获取聊天记录
        getChatRecord = function (boardId, wechatId, friendId, Old) {
            var lastId = 0;
            var obj = $('#friendChat_' + wechatId + '_' + friendId).find('.layim-chat-main');
            obj.find('.load-more-message').css('display', 'none');
            obj.find('.loading-more-message').css('display', 'block');
            if (Old == true) {
                var ulObj = obj.find('ul');
                var first = ulObj.find('li').first();
                if (first.is('li')) {
                    // console.log(first.html());
                    lastId = first.attr('id');
                    lastId = lastId.replace('record_', '');
                    lastId = Number(lastId);
                }
            }
            service.post('api/v1/wxinfo/historymsg', {
                id: parseInt(boardId),
                page: 1,
                wxId: friendId
            }).then((res) => {
                if (res.code === 0) {
                    var msgs = res.data;
                    if (msgs) {
                        $.each(msgs.history, function (i, msg) {
                            new_msg(msg, false, msgs.wxId);
                        });
                    } else {
                        var noMoreMsg = '没有更多记录了';
                        obj.find('.layui-flow-more').html(noMoreMsg);
                    }
                    obj.find('.load-more-message').css('display', 'block');
                    obj.find('.loading-more-message').css('display', 'none');
                } else {
                    layer.msg(res.msg, {offset: '45vh', icon: 5, time: 2000});
                    obj.find('.load-more-message').css('display', 'block');
                    obj.find('.loading-more-message').css('display', 'none');
                }
            }).catch((err) => {
                layer.msg(err.msg, {offset: '45vh', icon: 5, time: 2000});
            })

        };

        var syncFriendInfo = function (wechatId, friendId) {
            $.ajax({
                type: "GET",
                url: "/cs_work/newFriendInfoTask/" + wechatId + "/" + friendId,
                success: function (response) {
                    var dataObj = {"code": -1, "msg": "\u8bf7\u6c42\u540c\u6b65\u597d\u53cb\u4fe1\u606f\u5931\u8d25"};
                    if (dataObj.code === 0) {

                    } else {
                        // layer.msg(dataObj.msg, {icon: 5});
                    }
                },
                error: function (request, status, error) {
                    // layer.msg('哦噢，网络开小差了', {icon: 5});
                }
            });
        };

        showChatRecords = function (boardId, wechatId, friendId, friendName, friendType, id) {
            var boardObj = $('#board' + boardId);
            var board_html = '';
            var getTpl = tpl_chat_records.innerHTML;
            var data = {"friend_name": friendName, 'friend_id': friendId, 'wechat_id': wechatId, "board_id": boardId};
            laytpl(getTpl).render(data, function (html) {
                board_html = $.trim(html);
            });
            var obj = boardObj.find('.layim-chat-box');
            obj.html(board_html);
            freshChartRecords(boardId, wechatId, friendId);

            var height = $('#LAY_wechat_content').height();
            var chatMainHeight = (height - 60 - 21 - 20 - 38 - 174 - 38 - 1 + 15 + 10);
            $('#friendChatRecord_' + wechatId + '_' + friendId).height(chatMainHeight);
            addNewChat(wechatId, friendId, false);
            // showDot(false, wechatId, friendId);
            hotkeySend(boardId, wechatId, friendId);
            getCustomerInfo(boardId, wechatId, friendId);
            showMoreWindow(wechatId, 2);
            // getMaterialGroups(wechatId, friendId);
            showSendImg(boardId, wechatId, friendId);

            var snsTab = boardObj.find('li[name=snsTab]');
            snsTab.attr('friend_id', friendId);
            var materialTab = boardObj.find('li[name=materialTab]');
            materialTab.attr('friend_id', friendId);
        };

        showSnsTabContent = function (wechatId) {
            var snsTab = $('#snsTab_' + wechatId);
            var friendId = snsTab.attr('friend_id');
            getFriendSnsPages(wechatId, friendId);
        };

        showMaterialTabContent = function (wechatId) {
            var materialTab = $('#materialTab_' + wechatId);
            var friendId = materialTab.attr('friend_id');
            console.log('showMaterialTabContent:' + wechatId + ',' + friendId);
            getMaterialGroups(wechatId, friendId);
        };

        var showMoreWindow = function (wechatId, friendType) {
            var moreWindowObj = $('#board' + wechatId).find('.wechat_board_right_more_window');
            if (friendType == 2) {
                moreWindowObj.css('display', 'block');
            } else {
                moreWindowObj.css('display', 'none');
            }
        };

        var freshChartRecords = function (boardId, wechatId, friendId) {
            getChatRecord(boardId, wechatId, friendId);
        };

        showFriendInfo = function (boardId, wechatId, friendId, nickName, remark, avatar, province, city, sex, id) {
            var board_html = '';
            var getTpl = tpl_friend_info.innerHTML;
            const friendInfo = {
                boardId: boardId,
                wechatId: wechatId,
                friendId: friendId,
                nickName: nickName,
                avatar: avatar,
                province: province,
                remark: remark,
                city: city,
                sex: sex,
                id: id
            }
            var data = {'friend_id': friendId, 'wechat_id': wechatId, 'friendInfo': friendInfo};
            laytpl(getTpl).render(data, function (html) {
                board_html = $.trim(html);
            });
            var obj = $('#board' + boardId).find('.layim-friend-info');
            obj.html(board_html);
        };

        sendMsgToFriend = function (boardId, wechatId, friendId, friendName, friendType) {
            showChatWindow('board' + boardId, boardId, false, friendId);
            showChatRecords(boardId, wechatId, friendId, friendName, friendType, true);
        };

        deleteFriend = function (friendId, friendName) {
            layer.confirm('您确定要删除好友 ' + friendName + ' ？', {
                btn: ['确定删除', '取消'] //按钮
            }, function () {
                service.delete('api/v1/wxfriend/' + friendId).then((res) => {
                    if (res.code === 200) {
                        layer.msg('删除成功', {offset: '45vh', icon: 1, time: 2000});
                    } else {
                        layer.msg(res.msg, {offset: '45vh', icon: 5, time: 2000});
                    }
                }).catch((err) => {
                    layer.msg(err.msg, {offset: '45vh', icon: 5, time: 2000});
                })
            });
        };

        getStrangers = function (wechatId) {
//            var obj = $('#board' + wechatId).find('input[name=search_friend]');
//            var search_friend = obj.val();
            var post = {
//                search: encodeURIComponent(search_friend),
                page: 1,
                limit: 10
            };
            $.ajax({
                type: "POST",
                url: "/cs_work/get_strangers_ajax/" + wechatId,
                data: post,
                success: function (response) {
                    var dataObj = $.parseJSON(response);
                    var dataObj = {"code": 0, "data": [], "pages": 0};
                    if (dataObj.code === 0) {
                        var strangers = dataObj.data;
                        freshStrangers(strangers, wechatId);
                    } else {
                        layer.msg(dataObj.msg, {icon: 5});
                    }
                },
                error: function (request, status, error) {
                    layer.msg('哦噢，网络开小差了', {icon: 5});
                }
            });
        };

        var freshStrangers = function (strangers, wechatId) {
            var board_html = '';
            var getTpl = tpl_stranger_list.innerHTML;
            var data = {"list": strangers, 'wechat_id': wechatId};
            laytpl(getTpl).render(data, function (html) {
                board_html = $.trim(html);
            });
            var obj = $('#board' + wechatId).find('.wechat_stranger_list');
            if (board_html && board_html != '') {
                obj.html(board_html);
            } else {
                obj.html('');
            }
        };

        getStrangerInfo = function (wechatId, strangerId) {
            showStrangerItemDot(false, strangerId);
            showStrangerDot(false, wechatId);
            showStrangerTabDot(false, wechatId);
            $.ajax({
                type: "GET",
                url: "/cs_work/get_stranger_info_ajax/" + wechatId + "/" + strangerId,
                success: function (response) {
                    var dataObj = $.parseJSON(response);
                    if (dataObj.code === 0) {
                        var strangerInfo = dataObj.data;
                        showStrangerInfo(wechatId, strangerId, strangerInfo);
                    } else {
                        layer.msg(dataObj.msg, {icon: 5});
                    }
                },
                error: function (request, status, error) {
                    layer.msg('哦噢，网络开小差了', {icon: 5});
                }
            });
        };

        showStrangerInfo = function (wechatId, strangerId, strangerInfo) {
            var board_html = '';
            var getTpl = tpl_stranger_info.innerHTML;
            var data = {'id': strangerId, 'wechat_id': wechatId, 'strangerInfo': strangerInfo};
            laytpl(getTpl).render(data, function (html) {
                board_html = $.trim(html);
            });
            var obj = $('#board' + wechatId).find('.layim-friend-info');
            obj.html(board_html);
        };

        acceptStranger = function (strangerId) {
            $.ajax({
                type: "GET",
                url: "/cs_work/newAcceptFriendTask/" + strangerId,
                success: function (response) {
                    var dataObj = $.parseJSON(response);
                    if (dataObj.code === 0) {
                        layer.msg('通过请求已提交', {icon: 1});
                    } else {
                        layer.msg(dataObj.msg, {icon: 5});
                    }
                },
                error: function (request, status, error) {
                    layer.msg('哦噢，网络开小差了', {icon: 5});
                }
            });
        };

        replyStranger = function (wechatId, strangerId) {
            var board_html = '';
            var getTpl = tpl_reply_stranger.innerHTML;
            var data = {'stranger_id': strangerId};
            laytpl(getTpl).render(data, function (html) {
                board_html = $.trim(html);
            });
            layer.open({
                title: '回复好友验证申请'
                , type: 1
                , area: '300px'
                //,skin: 'layui-layer-rim'
                , shadeClose: true
                , content: board_html
                , btn: ['确定回复', '取消']
                , yes: function (index, layero) {
                    var idObj = layero.find('input[name=stranger_id]');
                    var stranger_id = idObj.val();
                    var replyObj = layero.find('textarea[name=reply_stranger]');
                    var replyContent = replyObj.val();
                    if (replyContent && replyContent.length > 0) {
                        if (replyContent.length > 50) {
                            layer.msg('验证内容不能超过50个字', {icon: 5});
                            return false;
                        }
                        var post = {
                            replyContent: encodeURIComponent(replyContent)
                        };
                        $.ajax({
                            type: "POST",
                            url: "/cs_work/newAcceptFriendTask/" + stranger_id,
                            data: post,
                            success: function (response) {
                                var dataObj = $.parseJSON(response);
                                if (dataObj.code === 0) {
                                    layer.msg('回复已发送', {icon: 1});
                                    layer.close(index);
                                    getStrangerInfo(wechatId, strangerId);
                                } else {
                                    layer.msg(dataObj.msg, {icon: 5});
                                }
                            },
                            error: function (request, status, error) {
                                layer.msg('哦噢，网络开小差了', {icon: 5});
                            }
                        });
                    } else {
                        layer.msg('请输入回复内容', {icon: 5});
                        return false;
                    }
                }
                , btn2: function (index, layero) {

                }
            });
        };

        showAddFriend = function (wechatId) {
            var board_html = '';
            var getTpl = tpl_add_friend.innerHTML;
            var data = {'wechat_id': wechatId};
            laytpl(getTpl).render(data, function (html) {
                board_html = $.trim(html);
            });
            layer.open({
                title: '加好友'
                , type: 1
                , area: '300px'
                , shadeClose: true
                , content: board_html
                , btn: ['发送', '取消']
                , yes: function (index, layero) {
                    var idObj = layero.find('input[name=wechat_id]');
                    var wechat_id = idObj.val();
                    var searchObj = layero.find('input[name=search_stranger]');
                    var search = searchObj.val();
                    var msgObj = layero.find('textarea[name=friend_msg]');
                    var friendMsg = msgObj.val();

                    if (search && search.length > 0) {

                    } else {
                        layer.msg('请输入手机号、微信号或QQ号', {icon: 5});
                        return false;
                    }
                    if (friendMsg && friendMsg.length > 0) {
                        if (friendMsg.length > 50) {
                            layer.msg('验证内容不能超过50个中文，100个字符', {icon: 5});
                            return false;
                        }
                        var post = {
                            content: friendMsg,
                            id: parseInt(wechat_id),
                            searchWxName: search
                        }
                        service.post('api/v1/wxfriend/addfriendreq', post).then((res) => {
                            if (res.code === 200) {
                                layer.msg('好友验证申请已发送', {offset: '45vh', icon: 1, time: 2000});
                                layer.close(index);
                            } else {
                                layer.msg(res.msg, {offset: '45vh', icon: 5, time: 2000});
                            }
                        }).catch((err) => {
                            layer.msg(err.msg, {offset: '45vh', icon: 5, time: 2000});
                        })
                    } else {
                        layer.msg('请输入验证信息', {icon: 5});
                        return false;
                    }
                }
            });
        };

        var getMediaLayer;
        getMedia = function (weChatId, recordId, type, imgId) {
            if (imgId > 0) {
                var midimg = $('#chatImg' + imgId).attr('midimg');
                if (midimg == 1) return;
            } else {
                getMediaLayer = layer.msg('正在获取...', {
                    shadeClose: false
                    , icon: 16
                    , shade: 0.01
                });
            }
            $.ajax({
                type: "GET",
                url: '/cs_work/getMedia/' + weChatId + '/' + recordId + '/' + type,
                success: function (response) {
                    var dataObj = $.parseJSON(response);
                    if (dataObj.code === 0) {
                        checkingDownloadStatus = false;
                        if (type == 'EMOTICON') {
                            var emoticonUrl = dataObj.emoticonUrl;
                            var imgObj = $('#chatImg' + imgId);
                            imgObj.attr('src', emoticonUrl);
                        } else {
                            setTimeout(function () {
                                checkDownloadStatus(weChatId, recordId, type, imgId);
                            }, 1000);
                        }
                    } else {
                        layer.msg(dataObj.msg, {icon: 5});
                    }
                },
                error: function (request, status, error) {
                    layer.msg('哦噢，网络开小差了', {icon: 5});
                }
            });
        };

        var checkDownloadStatus = function (weChatId, recordId, type, imgId) {
            if (imgId <= 0 && checkingDownloadStatus) return;
            checkingDownloadStatus = true;
            $.ajax({
                type: "GET",
                url: '/cs_work/checkDownloadStatus/' + weChatId + '/' + recordId + '/' + type,
                success: function (response) {
                    layer.close(getMediaLayer);
                    var dataObj = $.parseJSON(response);
                    if (dataObj.code === 0) {
                        var imgWidth = 200;
                        switch (type) {
                            case 'THUMB':
                                imgWidth = 100;
                            case 'MIDIMG':
                            case 'HDIMG':
                                if (imgId > 0) {
                                    var imgObj = $('#chatImg' + imgId);
                                    imgObj.attr('src', '/cs_work/downloadMedia/' + weChatId + '/' + recordId + '/' + type);
                                    imgObj.attr('midimg', '1');
                                    imgObj.attr('width', imgWidth + 'px');
                                } else {
                                    var json = '{"code":0,"msg":"","title":"浏览原图","id":1,"start":0,"data":[{"alt":"浏览原图","src":"' + '/cs_work/downloadMedia/' + weChatId + '/' + recordId + '/' + type + '","thumb":""}]}';
                                    layer.photos({
                                        photos: $.parseJSON(json) //格式见API文档手册页
                                    });
                                }
                                break;
                            case 'VIDEO':
                                var t = layer;
                                var playVideo;
                                var src = '/cs_work/downloadMedia/' + weChatId + '/' + recordId + '/' + type
                                    , e = document.createElement("video");
                                return e.play ? (t.close(playVideo),
                                    void (playVideo = t.open({
                                        type: 1,
                                        title: "播放视频",
                                        area: ["340px", "500px"],
                                        maxmin: !0,
                                        shade: !1,
                                        content: '<div style="background-color: #000; height: 100%;"><video style="position: absolute; width: 100%; height: 100%;" src="' + src + '" loop="loop" autoplay="autoplay"></video></div>'
                                    }))) : t.msg("您的浏览器不支持video");
                                break;
                            case 'FILE':
                                var href = '/cs_work/downloadMedia/' + weChatId + '/' + recordId + '/' + type;
                                window.open(href, '_blank');
                                break;
                        }
                    } else if (dataObj.code === 1) {
                        checkingDownloadStatus = false;
                        setTimeout(function () {
                            checkDownloadStatus(weChatId, recordId, type, imgId);
                        }, 1000);
                    } else {
                        checkingDownloadStatus = false;
                        layer.msg(dataObj.msg, {icon: 5});
                    }
                },
                error: function (request, status, error) {
                    layer.close(getMediaLayer);
                    checkingDownloadStatus = false;
                    layer.msg('哦噢，网络开小差了', {icon: 5});
                }
            });
        };

        getMediaV2 = function (imgId, mediaUrl, type, images, index) {
            layer.close(getMediaLayer);
            var imgWidth = 200;
            switch (type) {
                case 'THUMB':
                    imgWidth = 100;
                case 'MIDIMG':
                case 'HDIMG':
                    var jsonStr = '{"code":0,"msg":"","title":"","id":1,"start":0,"data":[{"alt":"","src":"' + mediaUrl + '","thumb":""}]}';
                    if (images) {
                        images = images.split(',');
                        var imageJsonStr = '';
                        layui.each(images, function (index, image) {
                            imageJsonStr += ',{"alt":"","src":"' + image + '","thumb":""}'
                        });
                        if (imageJsonStr != '') {
                            imageJsonStr = imageJsonStr.substr(1);
                            jsonStr = '{"code":0,"msg":"","title":"","id":1,"start":' + index + ',"data":[' + imageJsonStr + ']}';
                        }
                    }
                    var json = $.parseJSON(jsonStr);
                    layer.photos({
                        photos: json, //格式见API文档手册页
                        shift: 5
                    });
                    break;
                case 'VIDEO':
                    var t = layer;
                    var playVideo;
                    var e = document.createElement("video");
                    return e.play ? (t.close(playVideo),
                        void (playVideo = t.open({
                            type: 1,
                            title: "播放视频",
                            area: ["340px", "500px"],
                            maxmin: !0,
                            shade: !1,
                            content: '<div style="background-color: #000; height: 100%;"><video style="position: absolute; width: 100%; height: 100%;" src="' + mediaUrl + '" loop="loop" autoplay="autoplay"></video></div>'
                        }))) : t.msg("您的浏览器不支持video");
                    break;
                case 'FILE':
                    window.open(mediaUrl, '_blank');
                    break;
            }
        };

        getFriendSnsPages = function (weChatId, friendId) {//获取好友朋友圈
            var panelObj = $('#friend_sns_page_panel_' + weChatId);
            var winHeight = getWindowHeight();
            var panelHeight = winHeight - 60 - 41 - 10 - 41 - 10 - 10 - 40;
            panelObj.css('height', panelHeight + 'px');

            var listObj = $('#friend_sns_page_' + weChatId);
            listObj.html('');
            layui.use('flow', function () {
                var flow = layui.flow;
                var element = layui.element;
                element.init();

                flow.load({
                    elem: '#friend_sns_page_' + weChatId //指定列表容器
                    , scrollElem: '#friend_sns_page_panel_' + weChatId
                    , end: '已经拉到底了'
                    , done: function (page, next) { //到达临界点（默认滚动触发），触发下一页
                        var lis = [];
                        var post = {
                            id: parseInt(weChatId),
                            page: page
                        };

                        service.post('api/v1/wxinfo/viewfriendcircle', post).then((res) => {
                            //假设你的列表返回在data集合中
                            if (res.code === 200) {
                                var data = res.data.Data
                                var rows = data.ObjectList;
                                layui.each(rows, function (index, row) {
                                    var item = $.xml2json(row.objectDesc.buffer);
                                    var ContentObject = item.ContentObject;
                                    var contentStyle = ContentObject.contentStyle;
                                    var str = '<div class="layui-row layui-col-space2">';
                                    str += '<div class="snsPageContent">' + parseEmotion(item.contentDesc) + '</div>';
                                    if (ContentObject.mediaList) {
                                        var medias = ContentObject.mediaList.media;
                                        let arr = []
                                        if (medias.url) {
                                            arr = [medias]
                                        } else {
                                            arr = medias
                                        }
                                        var mediasStr = '';
                                        if (contentStyle === '3' || contentStyle === '5' || contentStyle === '26') {//外部内容
                                            if (contentStyle === '26') {
                                                layui.each(arr, function (index, media) {
                                                    mediasStr += '<img id="snsImg' + media.id + '" src="' + media.thumb.split('@')[0] + '" snsImg="0" height="30px"> ';
                                                });
                                            }
                                            str += '<div class="snsPageOutContent layui-text" style="padding:5px;background-color: #f0f0f0;"><a href="' + ContentObject.contentUrl + '" target="_blank">' + mediasStr + ContentObject.title + '</a></div>';
                                        } else if (contentStyle === '15') {//视频
                                            mediasStr += '<div class="snsPageMedia layui-row">';
                                            layui.each(arr, function (index, media) {
                                                mediasStr += '<div class="layui-col-md4" style="cursor: pointer;" onclick="viewOuterContent(\'' + media.url.split('@')[0] + '\');"><img src="' + media.thumb.split('@')[0] + '" height="80px"><i class="layui-icon layui-icon-video" style="position: absolute; top: 40%; left: 10%;z-index:2;font-size: 20px;color: #fff;"></i></div>';
                                            });
                                            str += mediasStr;
                                            str += '</div><br>';
                                        } else {
                                            mediasStr += '<div class="snsPageMedia layui-row">';
                                            var snsImages = []
                                            layui.each(arr, function (index, media) {
                                                snsImages.push(media.url.split('@')[0]);
                                            })
                                            var snsImageIndex = 0;
                                            layui.each(arr, function (index, media) {
                                                mediasStr += '<div class="layui-col-md4"><div class=" snsImgbox"><img id="snsImg' + media.id + '" src="' + media.thumb.split('@')[0] + '" snsImg="0" onclick="getMediaV2(' + weChatId + ', \'' + media.url.split('@')[0] + '\', \'HDIMG\', \'' + snsImages + '\', ' + snsImageIndex + ');"></div></div>';
                                                snsImageIndex++;
                                            });
                                            str += mediasStr;
                                            str += '</div><br>';
                                        }
                                    }
                                    str += '<div class="snsPageTime layui-word-aux">' + parseTime(item.createTime) + '</div>';
                                    str += '</div><hr>';
                                    lis.push(str);
                                })
                                next(lis.join(''), false);
                            } else {
                                layer.msg(res.msg, {offset: '45vh', icon: 5, time: 2000});
                            }
                        }).catch((err) => {
                            layer.msg(err.msg, {offset: '45vh', icon: 5, time: 2000});
                        })
                    }
                })
            })
        }

        getSnsMedia = function (weChatId, friendId, fileId, type, recordId) {
            if (type == 'THUMB') {
                var snsImg = $('#snsImg' + fileId + (recordId ? '_' + recordId : '')).attr('snsImg');
                if (snsImg == 1) return;
            }
            $.ajax({
                type: "GET",
                url: '/cs_work/getMediaSns/' + weChatId + '/' + friendId + '/' + fileId + '/' + type,
                success: function (response) {
                    var dataObj = $.parseJSON(response);
                    if (dataObj.code === 0) {
                        checkingSnSDownloadStatus = false;
                        setTimeout(function () {
                            checkSnsMediaDownloadStatus(fileId, type, recordId);
                        }, 1000);
                    } else if (dataObj.code === -1) {
                        layer.msg(dataObj.msg, {icon: 5});
                    } else {
                        checkingSnSDownloadStatus = false;
                        layer.msg(dataObj.msg, {icon: 5});
                    }
                },
                error: function (request, status, error) {
                    layer.msg('哦噢，网络开小差了', {icon: 5});
                }
            });
        };

        var checkSnsMediaDownloadStatus = function (fileId, type, recordId) {
            // if (imgId <=0 && checkingSnSDownloadStatus) return;
            // checkingSnSDownloadStatus = true;
            $.ajax({
                type: "GET",
                url: '/cs_work/checkDownloadStatusSns/' + fileId + '/' + type,
                success: function (response) {
                    var dataObj = $.parseJSON(response);
                    if (dataObj.code === 0) {
                        switch (type) {
                            case 'THUMB':
                            case 'HDIMG':
                                if (type == 'THUMB') {
                                    var imgObj = $('#snsImg' + fileId + (recordId ? '_' + recordId : ''));
                                    imgObj.attr('src', '/cs_work/downloadMediaSns/' + fileId + '/' + type);
                                    imgObj.attr('snsImg', '1');
                                } else {
                                    var json = '{"code":0,"msg":"","title":"浏览原图","id":1,"start":0,"data":[{"alt":"浏览原图","src":"' + '/cs_work/downloadMediaSns/' + fileId + '/' + type + '","thumb":""}]}';
                                    layer.photos({
                                        photos: $.parseJSON(json) //格式见API文档手册页
                                    });
                                }
                                break;
                        }
                    } else if (dataObj.code === 1) {
                        checkingSnSDownloadStatus = false;
                        setTimeout(function () {
                            checkSnsMediaDownloadStatus(fileId, type, recordId);
                        }, 1000);
                    } else {
                        checkingSnSDownloadStatus = false;
                        layer.msg(dataObj.msg, {icon: 5});
                    }
                },
                error: function (request, status, error) {
                    checkingSnSDownloadStatus = false;
                    layer.msg('哦噢，网络开小差了', {icon: 5});
                }
            });
        };

        viewOuterContent = function (url) {
            layer.open({
                title: ''
                , type: 2
                , area: ['500px', '300px']
                , shadeClose: true
                , content: url
            });
        };

        getCustomerInfo = function (boardId, weChatId, friendId) {
            var panelObj = $('#customer_info_panel_' + weChatId);
            var winHeight = getWindowHeight();
            var panelHeight = winHeight - 60 - 41 - 10 - 41 - 10 - 10 - 40;
            panelObj.css('height', panelHeight + 'px');
            service.post('api/v1/wxinfo/getcontractdetaillist', {
                id: parseInt(boardId),
                wxId: friendId
            }).then((res) => {
                if (res.code === 200) {
                    showCustomerInfo(weChatId, friendId, res.data);
                } else {
                    layer.msg(res.msg, {offset: '45vh', icon: 5, time: 2000});
                }
            }).catch((err) => {
                layer.msg(err.msg, {offset: '45vh', icon: 5, time: 2000});
            })
        }


        showCustomerInfo = function (wechatId, friendId, customerInfo) {
            var board_html = '';
            var getTpl = tpl_customer_info.innerHTML;
            var data = {'friend_id': friendId, 'wechat_id': wechatId, 'customerInfo': customerInfo};
            laytpl(getTpl).render(data, function (html) {
                board_html = $.trim(html);
            });
            var obj = $('#board' + wechatId).find('.layim-customer-info');
            obj.html(board_html);
        };

//Bof -- 快捷回复
        getMaterialGroups = function (weChatId, friendId) {
            $.ajax({
                type: "GET",
                url: "/cs_work/materialGroup",
                success: function (response) {
                    var dataObj = $.parseJSON(response);
                    if (dataObj.code === 0) {
                        var materialGroups = dataObj.data;
                        showMaterialGroup(weChatId, friendId, materialGroups);
                    } else {
                        // layer.msg(dataObj.msg, {icon: 5});
                    }
                },
                error: function (request, status, error) {
                    // layer.msg('哦噢，网络开小差了', {icon: 5});
                }
            });
        };

        var showMaterialGroup = function (weChatId, friendId, materialGroups) {
            var board_html = '';
            var getTpl = tpl_material_group.innerHTML;
            var data = {'friend_id': friendId, 'wechat_id': weChatId, 'materialGroups': materialGroups};
            laytpl(getTpl).render(data, function (html) {
                board_html = $.trim(html);
            });
            var obj = $('#quick_reply_groups_' + weChatId);
            obj.html(board_html);
            element.init();
        };

        getMaterials = function (weChatId, friendId, groupId) {
            $.ajax({
                type: "GET",
                url: "/cs_work/materialListData/" + groupId + "?status=1",
                success: function (response) {
                    var dataObj = $.parseJSON(response);
                    if (dataObj.code === 0) {
                        var materials = dataObj.data;
                        showMaterial(weChatId, friendId, materials);
                    } else {
                        // layer.msg(dataObj.msg, {icon: 5});
                    }
                },
                error: function (request, status, error) {
                    // layer.msg('哦噢，网络开小差了', {icon: 5});
                }
            });
        };

        var showMaterial = function (weChatId, friendId, materials) {
            var board_html = '';
            var getTpl = tpl_material.innerHTML;
            var data = {'friend_id': friendId, 'wechat_id': weChatId, 'materials': materials};
            laytpl(getTpl).render(data, function (html) {
                board_html = $.trim(html);
            });
            var obj = $('#quick_reply_' + weChatId);
            obj.html(board_html);
        };

        sendMaterial = function (weChatId, friendId, materialId) {
            var materialTab = $('#materialTab_' + weChatId);
            var theFriendId = materialTab.attr('friend_id');
            if (theFriendId > 0) {
                friendId = theFriendId;
            }
            var post = {
                id: materialId,
                weChatId: weChatId,
                friendId: friendId
            };
            $.ajax({
                type: "POST",
                url: "/cs_work/materialSend",
                data: post,
                success: function (response) {
                    var dataObj = $.parseJSON(response);
                    if (dataObj.code == 0) {
                        layer.msg('发送中...', {icon: 1});
                    } else {
                        layer.msg(dataObj.msg, {icon: 5});
                    }
                },
                error: function (request, status, error) {

                }
            });
        };
//Eof -- 快捷回复

//发送图片
        showSendImg = function (boardId, weChatId, friendId) {
            const obj = $('#sendImg_' + weChatId + '_' + friendId)
            obj.change(function (e) {
                var image = e.target.files[0]; //获取文件域中选中的图片
                var reader = new FileReader(); //实例化文件读取对象
                reader.readAsDataURL(image); //将文件读取为 DataURL,也就是base64编码
                reader.onload = function (ev) { //文件读取成功完成时触发
                    var dataURL = ev.target.result; //获得文件读取成功后的DataURL,也就是base64编码
                    layer.load(); //上传loading
                    service.post('api/v1/wxinfo/sendimagemsg', {
                        base64: dataURL, id: parseInt(boardId), searchWxIds: [friendId]
                    }).then((res) => {
                        if (res.code === 200) {
                            layer.closeAll('loading'); //关闭loading
                        } else {
                            layer.msg('发送失败', {icon: 5});
                        }
                    }).catch((err) => {
                        layer.msg('发送失败', {icon: 5});
                    })
                }
            })

        };

//标记消息已读
        setMsgRead = function (weChatId, friendId) {
            var post = {
                weChatId: weChatId,
                friendId: friendId
            };
            $.ajax({
                type: "POST",
                // url: "/cs_work/setMsgRead",
                url: "",
                data: post,
                success: function (response) {

                },
                error: function (request, status, error) {

                }
            });
        };

//快捷键发送
        var hotkeySend = function (boardId, wechatId, friendId) {
            var charRecord = $('#friendChat_' + wechatId + '_' + friendId);
            if (charRecord.is('div')) {
                var textarea = charRecord.find('.new-chat-message');
                textarea.focus();
                textarea.off('keydown').on('keydown', function (e) {
                    // var local = layui.data('layim')[cache.mine.id] || {};
                    var keyCode = e.keyCode;
                    // if(local.sendHotKey === 'Ctrl+Enter'){
                    //     if(e.ctrlKey && keyCode === 13){
                    //         sendMessage();
                    //     }
                    //     return;
                    // }
                    if (keyCode === 13) {
                        // if (e.ctrlKey) {
                        //     return textarea.val(textarea.val() + '\n');
                        // }
                        if (e.shiftKey) return;
                        e.preventDefault();
                        sendMsg(boardId, wechatId, friendId);
                    }
                });
            }
        };

        var getWindowHeight = function () {
            //获取浏览器窗口高度
            var winHeight = 0;
            if (window.innerHeight)
                winHeight = window.innerHeight;
            else if ((document.body) && (document.body.clientHeight))
                winHeight = document.body.clientHeight;
            //通过深入Document内部对body进行检测，获取浏览器窗口高度
            if (document.documentElement && document.documentElement.clientHeight)
                winHeight = document.documentElement.clientHeight;
            return winHeight;
        };

        var autodivheight = function () { //函数：获取尺寸
            var winHeight = getWindowHeight();
            //DIV高度为浏览器窗口的高度
            // var height = (winHeight-60-44-15-41-20-3-25);
            var height = (winHeight - 60 - 44 - 41 - 20 - 2);
            var weChatListHeight = (winHeight - 60 - 45 - 40);
            document.getElementById("LAY_wechat_content").style.height = height + "px";
            document.getElementById("LAY_wechat_list").style.height = weChatListHeight + "px";

            $(".wechat_board_right_chat_friend").height(height + "px");
            $(".wechat_board_right_friend_list").height(height + "px");

            var chatListHeight = (height - 42 - 48);
            $(".wechat_chat_list").height(chatListHeight + "px");
            var strangerListHeight = (height - 42 - 48 - 42 - 42 - 15);
            $(".wechat_stranger_list").height(strangerListHeight + "px");
            var friendListHeight = (height - 42 - 48 - 42 - 42 - 15);
            $(".wechat_friend_list").height(friendListHeight + "px");
            var tagListHeight = (height - 42 - 48);
            $(".tag_list").height(tagListHeight + "px");
        };
        autodivheight();
        window.onresize = autodivheight; //浏览器窗口发生变化时同时变化DIV高度

        getWeChats();
    }
)
;
